class SpamController < ApplicationController
  layout false
  before_filter :brute_force_check, :except => ['banned']

  def brute_force_check
    unless session[:spam]
      return true
    end
    if session[:spam][:failures] && session[:spam][:failures] >= SPAM_ATTEMPTS
      session[:spam][:failures] = 0
      session[:spam][:banned] = SPAM_BANTIME.minutes.from_now
    end
    
    if session[:spam][:banned] && session[:spam][:banned] > Time.now
      redirect_to :action => :banned
      return false
    else
      return true
    end
  end

  def banned
    @bantime = session[:spam][:banned]
  end

  def start
    session[:spam_trusted] = false
    session[:spam] = {}
    session[:spam][:failures] = 0 unless session[:spam][:failures]
    reset_guide
    generate
  end

  def respond
    if session[:spam][:last_issued] == params[:id].to_i
      session[:spam][:correct] += 1
    end
    reset_challange

    session[:spam][:step] += 1

    if session[:spam][:step] >= SPAM_CHALLANGES
      session[:spam_trusted] = session[:spam][:correct] >= SPAM_CHALLANGES
      if (!session[:spam_trusted])
        #logger.debug "corr: #{session[:spam][:correct]}"
        reset_guide
        @number_of_questions = SPAM_CHALLANGES
        session[:spam][:failures] += 1
        #render :action => :failed
        redirect_to :action => :failed
      else
        redirect_to session[:spam_return]
      end
    else
      reset_challange
      generate
    end
  end

  def generate
    session[:spam][:last_challange] = rand(10) unless session[:spam][:last_challange]

    if session[:spam][:last_challange] > 6
      redirect_to :action => :position
    else
      redirect_to :action => :aspect
    end
  end

  def position
    @number_of_steps = SPAM_CHALLANGES
    @this_step = session[:spam][:step]+1
    dont_use = session[:spam][:last_issued]
    (session[:spam][:last_issued] = rand(8)) while (session[:spam][:last_issued] == dont_use) unless session[:spam][:last_issued]
    @correct = session[:spam][:last_issued]
  end

  def aspect
    @number_of_steps = SPAM_CHALLANGES
    @this_step = session[:spam][:step]+1
    @timestamp = Time.now.to_f
  end

  def aspect_image
    unless session[:spam][:last_issued]
      session[:spam][:last_issued] = rand(2) 
      images = []
      if (session[:spam][:last_issued] == 0)
        images = Spam.get_normal_images
      else
        images = Spam.get_180_images
      end
      
      session[:spam][:last_aspect] = images[rand(images.length)]
    end
   
    send_data(
      File.read(session[:spam][:last_aspect]),
      :type => 'image/jpeg',
      :filename => "noname.jpg",
      :disposition => 'inline'
    )
  end

  def failed

  end

  protected
  def reset_guide
    session[:spam][:step] = 0
    session[:spam][:correct] = 0
    reset_challange
  end

  protected
  def reset_challange
    session[:spam][:last_issued] = nil
    session[:spam][:last_issued] = nil
    session[:spam][:last_challange] = nil
  end

end
